package com.cn.onetrip.activity;

import java.util.ArrayList;
import java.util.List;

import com.cn.onetrip.adapter.RouteItemAdapter;
import com.cn.onetrip.objects.ArticleListObj;
import com.cn.onetrip.objects.VisitsListObj;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.ActivityTag;
import com.cn.onetrip.untility.SysApplication;
import com.cn.onetrip.view.AdView;
import com.cn.onetrip.view.ContentScrollView;
import com.cn.onetrip.view.CustomMapView;
import com.cn.onetrip.view.SlideMenuLayout;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

public class RouteActivity extends Activity implements OnItemClickListener,
		OnScrollListener {

	private ListView viewRouteList;
	private RouteItemAdapter adapter;
	private Button quit;
	// public static View view;

	// private ImageView routeImage;
	private View footView;
	private View headView;
	private Handler handler;
	private int lastVisibleIndex;
	private boolean isOnRestart;
	private List<VisitsListObj> visitsList;
	private VisitsListObj visitsListObj;
	private List<ArticleListObj> detailedSites;
	private int RouteNum = 0;
	private LinearLayout linearLayoutMid;

	private RelativeLayout layoutTitle;
	private ContentScrollView scrollView;
	private AdView adView;

	private int mCount = 5;
	private int pagerIndex = 0;
	private ArrayList<View> menuViews = null;

	private ViewGroup main = null;
	private ViewPager viewPager = null;
	private ImageView imagePrevious = null;
	private ImageView imageNext = null;
	// private ImageView imageMapClick = null;

	private ImageButton adCancl;
	boolean isClick = false;

	private CustomMapView mapView = null;
	private ProgressBar pBar = null;
	private ImageView map_button;
	// private ImageView imageViewHead;

	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private boolean isViewable = false;
	private ListView mapping_listview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_route);
		if (SysApplication.routesList.size() == 0) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;

		layoutTitle = (RelativeLayout) findViewById(R.id.relativeLayoutTopMap);

		linearLayoutMid = (LinearLayout) findViewById(R.id.linearLayoutMid);
		footView = getLayoutInflater().inflate(R.layout.foot_view, null);
		handler = new Handler();

		mapping_listview = (ListView) findViewById(R.id.mapping_listview);

		viewRouteList = (ListView) findViewById(R.id.routeList);

		quit = (Button) findViewById(R.id.quit);
		quit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
				System.gc();
				overridePendingTransition(R.anim.push_left_translate,
						R.anim.pull_right_translate);
			}
		});

		visitsList = SysApplication.visitsListObj;
		mCount = visitsList.size();

		menuViews = new ArrayList<View>();
		SlideMenuLayout menu = new SlideMenuLayout(this, mhandler);
		if (mCount == 1) {
			String[][] menus = { { visitsList.get(0).name } };
			for (int i = 0; i < menus.length; i++) {
				menuViews.add(menu.getSlideMenuLinerLayout(menus[i],
						screenWidth));
			}
		} else {
			boolean isZero = (mCount % 2 == 0);
			int y = 0;
			if (isZero) {
				y = mCount / 2;
			} else {
				y = mCount / 2 + mCount % 2;
			}
			int count = 0;
			String[][] menus = new String[y][2];
			for (int i = 0; i < y; i++) {
				for (int j = 0; j < 2; j++) {
					if (!isZero && i == y - 1 && j == 1) {
						break;
					}
					menus[i][j] = visitsList.get(count).name;
					count++;
				}
			}
			for (int i = 0; i < menus.length; i++) {
				menuViews.add(menu.getSlideMenuLinerLayout(menus[i],
						screenWidth));
			}
		}

		LayoutInflater inflater = getLayoutInflater();

		if (mCount == 1) {
			headView = getLayoutInflater().inflate(R.layout.head_view, null);
			// headView.setVisibility(View.INVISIBLE);
			mapView = (CustomMapView) headView.findViewById(R.id.rout_map_view);
			// imageMapClick = (ImageView)
			// headView.findViewById(R.id.map_click);
			RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mapView
					.getLayoutParams();
			Params.width = getWindowManager().getDefaultDisplay().getWidth();
			Params.height = Params.width * 2 / 3;
			mapView.setLayoutParams(Params);
			map_button = (ImageView) headView.findViewById(R.id.map_button);
			pBar = (ProgressBar) headView.findViewById(R.id.progress_bar);
			viewRouteList.addHeaderView(headView);

		} else {
			main = (ViewGroup) inflater
					.inflate(R.layout.route_bar_layout, null);
			mapView = (CustomMapView) main.findViewById(R.id.rout_map_view);
			// imageMapClick = (ImageView) main.findViewById(R.id.map_click);
			RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mapView
					.getLayoutParams();
			Params.width = getWindowManager().getDefaultDisplay().getWidth();
			Params.height = Params.width * 2 / 3;
			mapView.setLayoutParams(Params);
			map_button = (ImageView) main.findViewById(R.id.map_button);
			pBar = (ProgressBar) main.findViewById(R.id.progress_bar);

			imagePrevious = (ImageView) main
					.findViewById(R.id.ivPreviousButton);
			imageNext = (ImageView) main.findViewById(R.id.ivNextButton);
			imagePrevious
					.setOnClickListener(new ImagePreviousOnclickListener());
			imageNext.setOnClickListener(new ImageNextOnclickListener());
			if (menuViews.size() > 1) {
				imageNext.setVisibility(View.VISIBLE);
			}
			viewPager = (ViewPager) main.findViewById(R.id.slideMenu);
			viewPager.setAdapter(new SlideMenuAdapter());
			viewPager.setOnPageChangeListener(new SlideMenuChangeListener());

			viewRouteList.addHeaderView(main);
		}

		mapView.setVisibility(View.INVISIBLE);
		map_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (isClick) {
					return;
				}
				isClick = true;
				Intent intent = new Intent();
				intent.putExtra("route_index", RouteNum);
				intent.setClass(RouteActivity.this, CustomMapActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.push_right_translate,
						R.anim.pull_left_translate);
			}
		});

		// imageViewHead = (ImageView) findViewById(R.id.imageViewHead);
		adapter = new RouteItemAdapter(RouteActivity.this, viewRouteList,
				mhandler);
		loadDate(RouteNum);

		mapping_listview.addFooterView(footView);
		mapping_listview.setAdapter(adapter);
		mapping_listview.setOnScrollListener(this);

		RouteItemAdapter.isVisiable = true;
		viewRouteList.addFooterView(footView);
		viewRouteList.setAdapter(adapter);
		// new Untility().setListViewHeightBasedOnChildren(viewRouteList);
		viewRouteList.setOnItemClickListener(this);
		viewRouteList.setOnScrollListener(this);

		adView = (AdView) findViewById(R.id.ad_view);
		// scrollView = (ContentScrollView) findViewById(R.id.scrollContent);
		// new TitleScrollManager(layoutTitle, adView, scrollView, null);

	}

	@Override
	protected void onResume() {
		super.onResume();
		RouteItemAdapter.isRefresh = false;
		isClick = false;
		if (!isOnRestart && SysApplication.advertsList.size() != 0) {
			isOnRestart = false;
		}
		adView.startTimer();
		loadingMap();
		mapView.setVisibility(View.INVISIBLE);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		isOnRestart = true;
	}

	@Override
	protected void onPause() {
		adView.stopTimer();
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		adapter.clean();
		adapter.threadQuit();
		mapView.onDestroy();
		super.onDestroy();
	}

	public void loadDate(int routeNum) {
		RouteNum = routeNum;
		visitsListObj = visitsList.get(routeNum);
		detailedSites = visitsListObj.detailedsSites;
		if (detailedSites.size() <= 6) {

		}
		int typeCount = 0;
		for (int i = 0; i < detailedSites.size(); i++) {
			ArticleListObj articleListObj = detailedSites.get(i);
			if (articleListObj.type_cd != 0) {
				typeCount++;
			}
			adapter.addRoute(articleListObj.icon, articleListObj.title,
					articleListObj.description, articleListObj.distance,
					articleListObj.spendTime, articleListObj.type_cd);
		}
		adapter.setTypeCount(typeCount);
		adapter.notifyDataSetChanged();
	}

	private void loadingMap() {

		mapView.setData(SysApplication.routesList.get(RouteNum), mapHandler,
				false, mapView.getWidth(), mapView.getHeight());
		pBar.setVisibility(View.VISIBLE);
	}

	public Handler mapHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == CustomMapView.MAP_LOAD_FAIL) {
				mapView.setBackgroundResource(R.drawable.default_image_big);
			} else if (msg.what == CustomMapView.MAP_LOAD_SUCCESS) {
				mapView.setVisibility(View.VISIBLE);
				// imageMapClick.setVisibility(View.VISIBLE);
			}

			pBar.setVisibility(View.GONE);
			// headView.startAnimation(animation);
		};
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_left_translate,
					R.anim.pull_right_translate);
		}
		return super.onKeyDown(keyCode, event);
	}

	// boolean isOpen = false;
	public Handler mhandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			for (int i = 0; i < visitsList.size(); i++) {
				if (msg.what == 10 + i) {
					RouteNum = i;
					adapter.clean();
					loadDate(i);
					// SysApplication.recycleBmpRoute();
					loadingMap();
					// viewRouteList.scrollTo(0, 0);
					return;
				} else if (msg.what == 3) {
					if (visibleItemCount == msg.arg1 + 2 && isViewable == false) {
						isViewable = true;
						final Animation anim1 = AnimationUtils.loadAnimation(
								getApplicationContext(), R.anim.alpha);
						final Animation anim2 = AnimationUtils.loadAnimation(
								getApplicationContext(), R.anim.translation);
						final Animation anim3 = AnimationUtils.loadAnimation(
								getApplicationContext(),
								R.anim.translation_mapping);
						anim1.setFillAfter(true);
						anim2.setFillAfter(true);
						anim3.setFillAfter(true);
						viewRouteList.startAnimation(anim2);
						mapping_listview.startAnimation(anim3);
						anim2.setAnimationListener(new AnimationListener() {

							@Override
							public void onAnimationStart(Animation animation) {
							}

							@Override
							public void onAnimationRepeat(Animation animation) {

							}

							@Override
							public void onAnimationEnd(Animation animation) {
								// if (!isOpen) {
								// isOpen = true;
								viewRouteList.clearAnimation();
								mapping_listview.clearAnimation();
								RouteItemAdapter.isRefresh = true;
								// }
								mapping_listview.setVisibility(View.GONE);
							}
						});
					}
				}
			}
		};
	};

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 > adapter.Models.size()) {
			// viewRouteList.setSelectionFromTop(1, 0);
			return;
		}
		ArticleListObj articleListObj = detailedSites.get(arg2 - 1);

		Intent intent = new Intent(getApplicationContext(),
				RouteAtlasActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("route_num", RouteNum);
		bundle.putInt("title_image", R.drawable.route_detail_title);
		bundle.putBoolean("Left", true);
		bundle.putString("module", ActivityTag.Route);
		bundle.putInt("itemId", arg2 - 1);
		bundle.putString("title", articleListObj.title);
		bundle.putString("time", articleListObj.time);
		bundle.putString("source", articleListObj.source);
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.push_right_translate,
				R.anim.pull_left_translate);
	}

	class SlideMenuAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return menuViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(menuViews.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(menuViews.get(arg1));

			return menuViews.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	class SlideMenuChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int arg0) {
			int pageCount = menuViews.size() - 1;
			pagerIndex = arg0;

			if (arg0 >= 0 && arg0 < pageCount) {
				imageNext.setVisibility(View.VISIBLE);
			} else {
				imageNext.setVisibility(View.INVISIBLE);
			}

			if (arg0 > 0 && arg0 <= pageCount) {
				imagePrevious.setVisibility(View.VISIBLE);
			} else {
				imagePrevious.setVisibility(View.INVISIBLE);
			}
		}
	}

	class ImageNextOnclickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			pagerIndex++;
			viewPager.setCurrentItem(pagerIndex);
		}
	}

	class ImagePreviousOnclickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			pagerIndex--;
			viewPager.setCurrentItem(pagerIndex);
		}
	}

	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem,
			int visibleItemCount, int arg3) {
		RouteItemAdapter.isRefresh = false;
		this.visibleItemCount = visibleItemCount;
		visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {

	}

}
